import React, { useState, useEffect } from 'react'
import { Card, Button, Space, Modal, message, Tabs, Descriptions, Tag, Row, Col, Tree } from 'antd'
import { PlusOutlined, EditOutlined, DeleteOutlined, BranchesOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import DataTable from '../../../components/common/DataTable'
import Form from '../../../components/common/Form'
// 引入API
import { getDepartments, createDepartment, getDepartment, updateDepartment, deleteDepartment } from '../../../api/department'

// 引入员工API
import { getEmployees } from '../../../api/employee'

const { confirm } = Modal

const Department = () => {
    const [loading, setLoading] = useState(false)
    const [dataSource, setDataSource] = useState([])
    const [treeData, setTreeData] = useState([])
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0
    })
    const [visible, setVisible] = useState(false)
    const [currentDepartment, setCurrentDepartment] = useState(null)
    const [viewVisible, setViewVisible] = useState(false)
    const [viewDepartment, setViewDepartment] = useState(null)

    // 员工数据状态
    const [employees, setEmployees] = useState([])

    useEffect(() => {
        fetchDepartments()
        fetchEmployees()
    }, [pagination.current, pagination.pageSize])

    // 获取部门数据
    const fetchDepartments = async () => {
        setLoading(true)
        try {
            const params = {
                page: pagination.current,
                pageSize: pagination.pageSize
            }
            const response = await getDepartments(params)
            setDataSource(response.data)
            setPagination({
                ...pagination,
                total: response.total
            })
            // 构建树形结构数据
            const tree = buildDepartmentTree(response.data)
            setTreeData(tree)
        } catch (error) {
            console.error('获取部门列表失败:', error)
            message.error('获取部门列表失败')
        } finally {
            setLoading(false)
        }
    }

    // 获取员工数据
    const fetchEmployees = async () => {
        try {
            const response = await getEmployees()
            setEmployees(response.data)
        } catch (error) {
            console.error('获取员工列表失败:', error)
            message.error('获取员工列表失败')
        }
    }

    // 构建部门树形结构
    const buildDepartmentTree = (departments) => {
        // 找出所有根部门（parent_id为0的部门）
        const rootDepartments = departments.filter(dept => dept.parent_id === 0)

        // 递归构建树形结构
        const buildTree = (parentId) => {
            const children = departments.filter(dept => dept.parent_id === parentId)
            if (children.length === 0) return []

            return children.map(child => ({
                key: child.id,
                title: child.name,
                children: buildTree(child.id)
            }))
        }

        return rootDepartments.map(root => ({
            key: root.id,
            title: root.name,
            children: buildTree(root.id)
        }))
    }

    // 处理表格变化
    const handleTableChange = (pagination) => {
        setPagination(pagination)
    }

    // 处理搜索
    const handleSearch = async (value) => {
        setLoading(true)
        try {
            const params = {
                page: pagination.current,
                pageSize: pagination.pageSize,
                keyword: value
            }
            const response = await getDepartments(params)
            setDataSource(response.data)
            setPagination({
                ...pagination,
                total: response.total
            })
        } catch (error) {
            console.error('搜索部门失败:', error)
            message.error('搜索部门失败')
        } finally {
            setLoading(false)
        }
    }

    // 添加部门
    const handleAdd = () => {
        setCurrentDepartment(null)
        setVisible(true)
    }

    // 编辑部门
    const handleEdit = async (record) => {
        try {
            setLoading(true)
            // 获取最新的部门详情
            const response = await getDepartment(record.id)
            setCurrentDepartment(response.data)
            setVisible(true)
        } catch (error) {
            console.error('获取部门详情失败:', error)
            message.error('获取部门详情失败')
        } finally {
            setLoading(false)
        }
    }

    // 查看部门详情
    const handleView = async (record) => {
        try {
            setLoading(true)
            // 获取最新的部门详情
            const response = await getDepartment(record.id)
            setViewDepartment(response.data)
            setViewVisible(true)
        } catch (error) {
            console.error('获取部门详情失败:', error)
            message.error('获取部门详情失败')
        } finally {
            setLoading(false)
        }
    }

    // 删除部门
    const handleDelete = (id) => {
        confirm({
            title: '确认删除',
            icon: <ExclamationCircleOutlined />,
            content: '确定要删除这个部门吗？此操作不可恢复，且会影响所有关联的员工。',
            onOk: async () => {
                try {
                    setLoading(true)
                    await deleteDepartment(id)
                    message.success('删除成功')
                    // 重新获取列表数据
                    fetchDepartments()
                } catch (error) {
                    console.error('删除部门失败:', error)
                    message.error('删除部门失败')
                } finally {
                    setLoading(false)
                }
            }
        })
    }

    // 表单提交
    const handleFormSubmit = async (values) => {
        try {
            setLoading(true)
            if (currentDepartment) {
                // 编辑部门
                await updateDepartment(currentDepartment.id, values)
                message.success('编辑成功')
            } else {
                // 添加部门
                await createDepartment(values)
                message.success('添加成功')
            }
            // 关闭模态框
            setVisible(false)
            // 重新获取列表数据
            fetchDepartments()
        } catch (error) {
            console.error('保存部门失败:', error)
            message.error('保存部门失败')
        } finally {
            setLoading(false)
        }
    }

    // 表格列定义
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
            width: 80
        },
        {
            title: '部门名称',
            dataIndex: 'name',
            key: 'name',
            render: (text, record) => (
                <a onClick={() => handleView(record)}>{text}</a>
            )
        },
        {
            title: '部门描述',
            dataIndex: 'description',
            key: 'description',
            ellipsis: true
        },
        {
            title: '部门主管',
            dataIndex: 'manager_name',
            key: 'manager_name'
        },
        {
            title: '上级部门',
            dataIndex: 'parent_id',
            key: 'parent_id',
            render: (parentId) => {
                if (parentId === 0) return '无'
                const parent = dataSource.find(dept => dept.id === parentId)
                return parent ? parent.name : '无'
            }
        },
        {
            title: '层级',
            dataIndex: 'level',
            key: 'level'
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (status) => {
                let color = status === 1 ? 'green' : 'volcano'
                let text = status === 1 ? '正常' : '禁用'
                return <Tag color={color}>{text}</Tag>
            }
        },
        {
            title: '操作',
            key: 'action',
            width: 180,
            render: (_, record) => (
                <Space size="middle">
                    <Button
                        type="text"
                        icon={<EditOutlined />}
                        onClick={() => handleEdit(record)}
                    >
                        编辑
                    </Button>
                    <Button
                        type="text"
                        danger
                        icon={<DeleteOutlined />}
                        onClick={() => handleDelete(record.id)}
                    >
                        删除
                    </Button>
                </Space>
            )
        }
    ]

    return (
        <div className="department-container">
            <Row gutter={[16, 16]}>
                <Col span={8}>
                    <Card title="部门结构" extra={<BranchesOutlined />}>
                        {treeData.length > 0 ? (
                            <Tree
                                treeData={treeData}
                                defaultExpandAll
                                showLine
                                showIcon
                            />
                        ) : (
                            <div style={{ textAlign: 'center', padding: '20px 0' }}>
                                暂无部门数据
                            </div>
                        )}
                    </Card>
                </Col>
                <Col span={16}>
                    <Card title="部门管理" extra={
                        <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
                            添加部门
                        </Button>
                    }>
                        <DataTable
                            columns={columns}
                            dataSource={dataSource}
                            loading={loading}
                            rowKey="id"
                            pagination={pagination}
                            onChange={handleTableChange}
                            onSearch={handleSearch}
                            onRefresh={fetchDepartments}
                            searchPlaceholder="搜索部门名称/描述/主管"
                        />
                    </Card>
                </Col>
            </Row>

            {/* 部门表单模态框 */}
            <Modal
                title={currentDepartment ? '编辑部门' : '添加部门'}
                open={visible}
                onCancel={() => setVisible(false)}
                footer={null}
                width={700}
            >
                <Form
                    initialValues={currentDepartment || { parent_id: 0, status: 1 }}
                    onFinish={handleFormSubmit}
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}
                >
                    <Form.Item
                        name="name"
                        label="部门名称"
                        rules={[{ required: true, message: '请输入部门名称' }]}
                    >
                        <input placeholder="请输入部门名称" />
                    </Form.Item>
                    <Form.Item
                        name="description"
                        label="部门描述"
                    >
                        <textarea placeholder="请输入部门描述" rows={4} />
                    </Form.Item>
                    <Form.Item
                        name="manager_id"
                        label="部门主管"
                        rules={[{ required: true, message: '请选择部门主管' }]}
                    >
                        <select>
                            <option value="">请选择部门主管</option>
                            {employees.map(emp => (
                                <option key={emp.id} value={emp.id}>{emp.name}</option>
                            ))}
                        </select>
                    </Form.Item>
                    <Form.Item
                        name="parent_id"
                        label="上级部门"
                        rules={[{ required: true, message: '请选择上级部门' }]}
                    >
                        <select>
                            <option value={0}>无（作为一级部门）</option>
                            {dataSource.map(dept => (
                                // 不能选择自己作为父部门
                                currentDepartment && dept.id === currentDepartment.id ? null :
                                    <option key={dept.id} value={dept.id}>{dept.name}</option>
                            ))}
                        </select>
                    </Form.Item>
                    <Form.Item
                        name="status"
                        label="状态"
                        rules={[{ required: true, message: '请选择状态' }]}
                    >
                        <select>
                            <option value={1}>正常</option>
                            <option value={0}>禁用</option>
                        </select>
                    </Form.Item>
                </Form>
            </Modal>

            {/* 部门详情模态框 */}
            <Modal
                title="部门详情"
                open={viewVisible}
                onCancel={() => setViewVisible(false)}
                footer={null}
                width={700}
            >
                {viewDepartment && (
                    <Descriptions bordered column={2}>
                        <Descriptions.Item label="ID">{viewDepartment.id}</Descriptions.Item>
                        <Descriptions.Item label="部门名称">{viewDepartment.name}</Descriptions.Item>
                        <Descriptions.Item label="部门描述" span={2}>{viewDepartment.description}</Descriptions.Item>
                        <Descriptions.Item label="部门主管">{viewDepartment.manager_name}</Descriptions.Item>
                        <Descriptions.Item label="上级部门">
                            {viewDepartment.parent_id === 0 ? '无' :
                                dataSource.find(dept => dept.id === viewDepartment.parent_id)?.name || '无'}
                        </Descriptions.Item>
                        <Descriptions.Item label="层级">{viewDepartment.level}</Descriptions.Item>
                        <Descriptions.Item label="状态">
                            <Tag color={viewDepartment.status === 1 ? 'green' : 'volcano'}>
                                {viewDepartment.status === 1 ? '正常' : '禁用'}
                            </Tag>
                        </Descriptions.Item>
                        <Descriptions.Item label="创建时间">{viewDepartment.created_at}</Descriptions.Item>
                        <Descriptions.Item label="更新时间">{viewDepartment.updated_at}</Descriptions.Item>
                    </Descriptions>
                )}
            </Modal>
        </div>
    )
}

export default Department